<template>
	<div class="box">
		<div class="title">
			<span class="tag"></span>
			下游报价
		</div>
		<div class="container">
			<FormItems
				ref="form"
				v-model="formData.plan"
				:form="formList"
				:state="state"
				labelWidth="120px">
				<template #labelPlanPaymentMethodType>
					<span>
						支付时间
						<el-tooltip class="item" effect="dark" content="自然月" placement="right">
							<template #content>
								<div class="labelPlanBillTypecontent">
									<div>先付：起租日前支付为先付</div>
									<br />
									<div>后付：每期租期结束日后支付</div>
								</div>
							</template>
							<i class="el-icon-info tip"></i>
						</el-tooltip>
					</span>
				</template>
				<template #labelPlanPeriod>
					<span>
						账期
						<el-tooltip class="item" effect="dark" content="自然月" placement="right">
							<template #content>
								<div class="labelPlanBillTypecontent">
									<div>
										账期：起租日算起向后允许客户欠款的日期，支付时间选择后付的，相当于已经给客户30天的账期。
									</div>
									<br />
									<br />
									<div><b>举例:</b></div>
									<div>
										起租日为8月1日，付款日在8月31日前,选【月先付】【账期】应录入为【30天】;
									</div>
									<div>
										起租日为8月1日，付款日在9月30日前,选【月后付】【账期】应录入为【30天】;或【月先付】60天
									</div>
									<div style="color: #ff4949">注意：要与合同条件一致</div>
								</div>
							</template>
							<i class="el-icon-info tip"></i>
						</el-tooltip>
					</span>
				</template>
				<template #labelPlanBillType>
					<span>
						账单生成方式
						<el-tooltip class="item" effect="dark" content="自然月" placement="right">
							<template #content>
								<div class="labelPlanBillTypecontent">
									<span>
										满月：起租日=8月8日，则满月计算是从8月8日开始到9月7日
										（推荐选择）；
									</span>

									<br />
									<br />
									<span>
										自然月：起租日=8月8日，则自然月计算是第一期是从8月8日开始到8月31日，第二期起是1日到31日，最后一期是1日到7日补齐第一期少的那几天。（不推荐）
									</span>
								</div>
							</template>
							<i class="el-icon-info tip"></i>
						</el-tooltip>
					</span>
				</template>
				<template #planBillType>
					<div>
						<div v-if="state == 'readonly'">
							{{
								formData.plan.planBillType == 1
									? '自然月'
									: formData.plan.planBillType == 2
									? '满月'
									: '-'
							}}
						</div>
						<el-radio-group
							v-else
							v-model="formData.plan.planBillType"
							:disabled="state === 'disabled' || state === 'readonly'">
							<el-radio label="2">满月</el-radio>
							<el-radio label="1">自然月</el-radio>
						</el-radio-group>
					</div>
				</template>
			</FormItems>
			<FormItems
				ref="form2"
				v-model="formData.plan"
				:form="formList2.oil"
				:state="state"
				labelWidth="120px"></FormItems>
			<FormItems
				ref="form3"
				v-model="formData.plan"
				:form="formList2.driver"
				:state="state"
				labelWidth="120px"></FormItems>
		</div>
	</div>
</template>

<script>
	import FormItems from '@/views/finance/manage/formItems/index.vue';
	export default {
		components: { FormItems },
		inject: ['details_forecast', 'dicts', 'details_config', '_currentFormData'],
		props: {
			value: {
				required: false,
			},
			state: {
				required: false,
			},
			type: {
				required: false,
			},
		},
		data() {
			return {};
		},
		computed: {
			formData: {
				get() {
					return this.useVModel.call(this);
					// return this.value;
				},
				set(val) {
					this.$emit('input', val);
				},
			},
			config() {
				return this.details_config();
			},
			details() {
				return this.details_forecast();
			},
			currentFormData() {
				return this._currentFormData();
			},
			show() {
				return this.details.rentType_raw == '2';
			},
			dict() {
				return this.dicts();
			},
			planTenancyTypeList() {
				return [
					{
						label: '6',
						value: '6',
					},
					{
						label: '12',
						value: '12',
					},
					{
						label: '24',
						value: '24',
					},
					{
						label: '36',
						value: '36',
					},
					{
						label: '48',
						value: '48',
					},
					{
						label: '60',
						value: '60',
					},
				];
			},
			formList() {
				/**
				 *  @param details - 总数居
				 *  @param businessSource - 1，自营 2，渠道
				 *  @param rentType_raw - 1 易租， 2 享租
				 *  @param carType - 1 新车， 2 旧车
				 *  @param carSourceType - 1 自购， 2 现有， 3 外部转租赁
				 */
				return [
					{
						label: '支付频率',
						type: 'select',
						selectList: this.dict?.type?.quota_plan_payment_frequency_type,
						prop: 'planPaymentFrequencyType',
						rules: true,
					},
					{
						label: '租赁期限(月）',
						prop: 'planTenancyType',
						type: 'select',
						selectList: this.planTenancyTypeList,
						state:
							this.type == 'preview'
								? 'readonly'
								: // : this.config?.quotationProductSchemeRule
								  //       ?.openTermModification == 1
								  // ? "write"
								  'write',
						rules: true,
						prototype: {
							allowCreate:
								this.config?.quotationProductSchemeRule?.openTermModification == 1,
						},
						event: {
							type: 'change',
							cb: row => {
								// if (
								//     !Reflect.has(this.formData, "insuranceConfList")
								// )
								//     return;
								// let num = 0;
								// if (!row.planTenancyType) {
								//     num = 0;
								// } else {
								//     num = Math.ceil(row.planTenancyType / 12);
								// }
								// let arr = [];
								// for (let i = 0; i < num; i++) {
								//     arr.push({
								//         tenancy: i + 1,
								//         purchaserType: "",
								//         compulsoryAmount: 0,
								//         carvesselAmount: 0,
								//         commercialAmount: 0,
								//     });
								// }
								// this.formData.insuranceConfList = arr;
							},
						},
					},
					{
						label: '支付时间',
						type: 'select',
						selectList: this.dict?.type?.quota_plan_payment_method,
						prop: 'planPaymentMethodType',
						rules: true,
						labelSlot: 'labelPlanPaymentMethodType',
					},
					{
						label: '保证金比例（%）',
						prop: 'planCashdepositProportion',
						type: 'input_number',
						show:
							this.config?.businessSource == '1' && this.details?.rentType_raw == '2',
						format: row => {
							return row.planCashdepositProportion ?? '-' + '%';
						},
						// keepRules: true,
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
					},

					{
						label: '合同保证金',
						prop: 'planContractCashdeposit',
						type: 'input_number',
						tag: 'price',
						// state:
						// 	this.type == 'preview'
						// 		? 'readonly'
						// 		: // this.config.businessSource == '1' && // 自营
						// 		//   this.details?.rentType_raw == '1' && //易租
						// 		this.config?.quotationProductSchemeRule
						// 				?.openContractDepositModification == 1
						// 		? 'write'
						// 		: 'disabled',

						show: this.config?.quotationProductSchemeAttributeOption?.hasContractDepositOptions?.includes(
							1,
						),
						// keepRules: true,
						formitemPrototype: {
							key:
								this.config?.quotationProductSchemeRule
									?.contractDepositMinimumRentMonths || this.type == 'preview'
									? 'readonly'
									: this.config?.quotationProductSchemeRule
											?.openContractDepositModification == 1
									? 'write'
									: 'disabled',
						},
						rules:
							this.config?.quotationProductSchemeRule
								?.openContractDepositModification == 1
								? [
										{
											required: true,
											message: '请输入合同保证金',
											trigger: 'blur',
										},
								  ]
								: [
										{
											required: true,
											message: '请输入合同保证金',
											trigger: 'blur',
										},
										{
											validator: (rule, value, callback) => {
												let priceLine = 0,
													monthRent = 0;
												let ratio =
													this.config?.quotationProductSchemeRule
														?.contractDepositMinimumRentMonths ?? 0;
												if (this.formData.plan?.planRent) {
													monthRent = this.toNumberExcept(
														this.formData.plan?.planRent,
														this.formData.plan
															?.planPaymentFrequencyType * 1,
													);
													if (monthRent) {
														priceLine = this.toNumberRide(
															monthRent,
															ratio,
														);
													}
												}
												if (!Number.isFinite(priceLine * 1)) {
													priceLine = 0;
												}

												if (
													this.formData?.plan?.planContractCashdeposit <
													priceLine.toFixed(2) * 1
												) {
													callback(
														new Error(
															`不能低于${ratio}个月月租金（￥${priceLine.toFixed(
																2,
															)}）`,
														),
													);
												} else {
													callback();
												}
											},
											trigger: 'blur',
										},
								  ],
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
						event: {
							type: 'change',
							cb: row => {
								if (this.notEmpty(row.planContractCashdeposit)) {
									this.formData.planConf.planContractCashdeposit_state =
										'changed';
								} else {
									this.formData.planConf.planContractCashdeposit_state = '';
								}
								this.$set(row, 'planCashdepositProportion', undefined);
							},
						},
					},
					{
						label: '违章保证金',
						prop: 'planViolationCashdeposit',
						type: 'input_number',
						tag: 'price',
						show:
							this.config.businessSource == '1' &&
							this.config?.quotationProductSchemeAttributeOption?.hasViolationDepositOptions?.includes(
								1,
							),
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
						rules: true,
						// keepRules: true,
						event: {
							type: 'change',
							cb: row => {
								if (this.notEmpty(row.planViolationCashdeposit)) {
									this.formData.planConf.planViolationCashdeposit_state =
										'changed';
								} else {
									this.formData.planConf.planViolationCashdeposit_state = '';
								}
							},
						},
					},

					{
						label: '预计起租日期',
						type: 'datePicker',
						prop: 'planTimeStart',
						rules: [
							{
								required: true,
								message: '请选择预计起租日期',
								trigger: 'change',
							},
						],
						format: row => {
							return this.A_formatTime(row.planTimeStart, 0);
						},
					},

					{
						label: '每期租金',
						prop: 'planRent',
						type: 'input_number',
						tag: 'price',
						state:
							this.type == 'preview'
								? 'readonly'
								: this.config?.internalRateOfReturnCalcMethod == 1
								? 'write'
								: 'readonly',
						formitemPrototype: {
							key:
								this.type == 'preview'
									? 'readonly'
									: this.config?.internalRateOfReturnCalcMethod == 1
									? 'write'
									: 'readonly',
						},
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
						// keepRules: true,
						rules: true,
						event: {
							type: 'change',
							cb: row => {
								// row.planRent_state = "change";
							},
						},
					},
					{
						label: '账期',
						prop: 'planPeriod',
						type: 'input_number',
						labelSlot: 'labelPlanPeriod',
					},

					{
						label: '账单生成方式',
						prop: 'planBillType',
						// type: 'radioGroup',
						// radioGroupList: this.dict?.type?.quota_plan_bill_type,
						rules: true,
						type: 'empty',
						slot: 'planBillType',
						labelSlot: 'labelPlanBillType',
					},

					{
						label: '公司投入总额',
						prop: 'planTotalInvestment',
						type: 'input_number',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
						show:
							this.config.businessSource == '1' && this.details?.rentType_raw == '2',
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
						// keepRules: true,
						tag: 'price',
					},

					{
						label: '首期租金比例（%）',
						prop: 'planFirstRentProportion',
						type: 'input_number',
						show: this.details?.rentType_raw == '2',
						prototype: {
							step: 0.00001,
							stepStrictly: true,
							precision: 5,
						},
						format: row => {
							return row.planFirstRentProportion ?? '-' + '%';
						},
					},
					{
						label: '首期租金',
						prop: 'planFirstRent',
						type: 'input_number',
						show: this.details?.rentType_raw == '2',
						tag: 'price',
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},

						event: {
							type: 'change',
							cb: row => {
								if (this.notEmpty(row.planFirstRent)) {
									this.formData.planConf.planFirstRent_state = 'changed';
								} else {
									this.formData.planConf.planFirstRent_state = '';
								}
								this.$set(row, 'planFirstRentProportion', undefined);
							},
						},
						// state:
						// 	this.type == 'preview'
						// 		? 'readonly'
						// 		: this.config?.quotationProductSchemeRule
						// 				?.openInitialRentModification == 1
						// 		? 'wirte'
						// 		: 'disabled',
						// keepRules: true,
						rules:
							this.config?.quotationProductSchemeRule?.openInitialRentModification ==
							1
								? [
										{
											required: true,
											message: '请输入首期租金',
											trigger: 'blur',
										},
								  ]
								: [
										{
											required: true,
											message: '请输入首期租金',
											trigger: 'blur',
										},
										{
											validator: (rule, value, callback) => {
												let priceLine = 0,
													monthRent = 0;
												let ratio =
													this.config?.quotationProductSchemeRule
														?.initialRentMinimumRentMonths ?? 0;
												if (this.formData.plan?.planRent) {
													monthRent = this.toNumberExcept(
														this.formData.plan?.planRent,
														this.formData.plan
															?.planPaymentFrequencyType * 1,
													);
													if (monthRent) {
														priceLine = this.toNumberRide(
															monthRent,
															ratio,
														);
													}
												}
												if (!Number.isFinite(priceLine)) {
													priceLine = 0;
												}
												if (
													this.formData.plan?.planFirstRent <
													priceLine.toFixed(2) * 1
												) {
													callback(
														new Error(
															`不能低于${ratio}个月月租金（￥${priceLine.toFixed(
																2,
															)}）`,
														),
													);
												} else {
													callback();
												}
											},
											trigger: 'blur',
										},
								  ],
					},

					{
						label: 'APR（%）',
						prop: 'planPricingIrr',
						type: 'input_number',
						min: this.config?.quotationProductSchemeRule?.irrLowerLimit * 1 ?? 0,
						max: 100,
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
						format: row => {
							return row.planPricingIrr ?? '-' + '%';
						},
						rules: true,
						show:
							(this.details?.rentType_raw == '2' &&
								this.type !== 'preview' &&
								this.config?.businessSource == '1') ||
							this.config?.internalRateOfReturnCalcMethod == 3,
					},

					{
						label: '残值比例（%）',
						prop: 'planResidualProportion',
						type: 'input_number',
						// min:
						// 	this.config?.quotationProductSchemeRule
						// 		?.finalPaymentLowerLimit ?? 0,
						// max:
						// 	this.config?.quotationProductSchemeRule
						// 		?.finalPaymentUpperLimit ?? Infinity,
						prototype: {
							step: 0.00001,
							stepStrictly: true,
							precision: 5,
						},
						format: row => {
							return row.planResidualProportion ?? '-' + '%';
						},
						rules: true,
						show: this.details?.rentType_raw == '2',
					},
					// {
					//     label: "尾款",
					//     type: "input_number",
					//     prop: "planBalancepayment",
					//     show: this.details?.rentType_raw == "2",
					//     state:
					//         this.type == "preview"
					//             ? "readonly"
					//             : this.config?.openFinalPaymentModification == 1
					//             ? "write"
					//             : "disabled",
					//     prototype: {
					//         step: 0.01,
					//         stepStrictly: true,
					//     },
					//     event: {
					//         type: "change",
					//         cb: (row) => {
					//             if (this.notEmpty(row.planBalancepayment)) {
					//                 this.formData.planConf.planBalancepayment_state =
					//                     "change";
					//             } else {
					//                 this.formData.planConf.planBalancepayment_state =
					//                     "";
					//             }
					//             this.$set(row, "planResidualProportion", undefined);
					//         },
					//     },
					// },
					{
						label: '残值金额',
						type: 'input_number',
						prop: 'planBalancepayment',
						// show: this.details?.rentType_raw == "2",
						state: 'readonly',
						// keepRules: true,
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
						tag: 'price',
						event: {
							type: 'change',
							cb: row => {
								if (this.notEmpty(row.planBalancepayment)) {
									this.formData.planConf.planBalancepayment_state = 'change';
								} else {
									this.formData.planConf.planBalancepayment_state = '';
								}
								this.$set(row, 'planResidualProportion', undefined);
							},
						},
					},
				];
			},
			formList2() {
				return {
					oil: [
						{
							label: '是否包油费',
							prop: 'planFuelType',
							type: 'radioGroup',
							radioGroupList: this.dict?.type?.quota_plan_fuel_type,
							rules: true,
							event: {
								type: 'change',
								cb: row => {
									row.planFuelFee = undefined;
									row.remark = undefined;
								},
							},
						},
						{
							label: '油费',
							prop: 'planFuelFee',
							type: 'input_number',
							show: this.formData.plan.planFuelType == '1',
							rules: true,
							tag: 'price',
							prototype: {
								step: 0.01,
								stepStrictly: true,
							},
						},
						{
							label: '备注',
							prop: 'remark',
							type: 'input',
							show: this.formData.plan.planFuelType == '1',
							placeholder: '请说明油费测算方法',
							rules: true,
						},
					],
					driver: [
						{
							label: '是否含司机',
							prop: 'planDriverType',
							type: 'radioGroup',
							radioGroupList: this.dict?.type?.quota_plan_driver_type,
							rules: true,
							event: {
								type: 'change',
								cb: row => {
									row.planDriverFee = undefined;
									row.planDriverAccessory = undefined;
								},
							},
						},

						{
							label: '司机费用',
							prop: 'planDriverFee',
							type: 'input_number',
							show: this.formData.plan?.planDriverType == '1',
							prototype: {
								step: 0.01,
								stepStrictly: true,
							},
							rules: true,
							tag: 'price',
						},
						{
							label: '上传司机费用附件',
							prop: 'planDriverAccessory',
							type: 'upload',
							show: this.formData.plan?.planDriverType == '1',
							rules: true,
							prototype: {
								listType: 'text',
								isShowTip: false,
								limit: 1,
							},
							// formitemPrototype: {
							//     style: {
							//         width: "100%",
							//     },
							// },
						},
					],
				};
			},
		},
		created() {
			if (!this.notEmpty(this.formData?.plan?.planDriverType)) {
				this.$set(this.formData.plan, 'planDriverType', '2');
			}
			if (!this.notEmpty(this.formData?.plan?.planFuelType)) {
				this.$set(this.formData.plan, 'planFuelType', '2');
			}
			// this.formData.plan.planDriverType ??= "2";
			// this.formData.plan.planFuelType ??= "2";
			// this.initFormList();
		},
		mounted() {
			this.$emitter.on('clearVaild_downStream', this.clearVaild_downStream);
		},
		methods: {
			clearVaild_downStream(props) {
				this.$refs.form?.form_clearValidate?.(props);
			},
			valid() {
				return new Promise(async resolve => {
					let result = true;
					let refs = Object.values(this.$refs);
					for (let index = 0; index < refs?.length; index++) {
						const ref = refs[index];
						if (Object.prototype.toString.call(ref) == '[object Array]') {
							for (let i = 0; i < ref.length; i++) {
								const element = ref[i];
								if (element?.valid) {
									let rc = await element?.valid?.();
									result = result && rc;
								}
								if (element?.validate) {
									let rf = await this._valid(ref);
									result = result && rf;
								}
								if (element?.form_validate) {
									let rf = await this._valid(ref, 'form_validate');
									result = result && rf;
								}
							}
						} else {
							if (ref?.valid) {
								let rc = await ref?.valid?.();
								result = result && rc;
							}
							if (ref?.validate) {
								let rf = await this._valid(ref);
								result = result && rf;
							}
							if (ref?.form_validate) {
								let rf = await this._valid(ref, 'form_validate');
								result = result && rf;
							}
						}
					}

					resolve(result);
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	.box {
		border-radius: 8px;
		background-color: #fff;
		.title {
			font-size: 14px;
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			color: #333333;
			line-height: 22px;
			padding-bottom: 15px;
			// border-bottom: 1px solid #e9e9e9;
			display: flex;
			align-items: center;
			.tag {
				width: 8px;
				height: 8px;
				background-color: #1890ff;
				border-radius: 100%;
				margin-right: 10px;
			}
			.price {
				font-size: 14px;
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				color: #1890ff;
				line-height: 20px;
				margin-left: 20px;
			}
		}
	}
	::v-deep .el-input-number {
		width: 100%;
		.el-input-number__decrease,
		.el-input-number__increase {
			display: none;
		}
		input {
			width: 100%;
			padding: 5px;
			text-align: left;
		}
	}
	.labelPlanBillTypecontent {
		width: 300px;
		span {
			text-indent: 4ch;
		}
	}
</style>
